app.controller("loginController", function ($scope, $http, $location) {
    //登陆方法验证
    $scope.login = function () {
        $http({
            method: "post",
            url: "/zzlp/login",
            data: {"name": $scope.jobId, "password": $scope.pwd}

        }).then(function successCallBack(response) {

            console.log(response.data);
            var user = response.data;
            if (user == null || user == "") {
                console.log('3');
                $scope.invalid = true;
            } else {
                console.log("4");
                $scope.invalid = false;
                //alert("登陆成功!");
                console.log("5");

                window.location = "/zzlp/html/home.html";

            }
        });
    }
    //  $scope.Data=socket.collection;

});

app.controller("chatController", function ($scope, $rootScope, MyData) {
    $scope.MyData = MyData;
    console.log(MyData)
    console.log($scope.MyData)
    //alert("aaaaa "+ $scope.MyData.collection);

});

app.controller("twitter", function ($scope, $rootScope, $http) {

    $rootScope.showDetail=function (name,time,content,dimgs,avatar,articleUrl,urlDisplay) {
        $rootScope.visiable=true;

        $rootScope.DName = name;
        $rootScope.DTime = time;
        $rootScope.DContent = content;
        $rootScope.DImgs = dimgs;
        $rootScope.DAvatar = avatar;
        $rootScope.DAtricleUrl = articleUrl;
        $rootScope.UrlDispaly = urlDisplay;


        $("#publishsaysay").hide();
        $("#DetailDiv").show();


        $scope.changePic = function ($event) {
            var img = $event.srcElement || $event.target;
            angular.element("#bigimage")[0].src = img.src;
            angular.element("#js-imgview")[0].style.display = "block";
            angular.element("#js-imgview-mask")[0].style.display = "block";
        }
        //点击图片时放小显示图片
        $scope.closePic = function () {
            angular.element("#js-imgview")[0].style.display = "none";
            angular.element("#js-imgview-mask")[0].style.display = "none";

        }

    }

    $scope.changePage = function () {

        $("#DetailDiv").hide();
        $("#publishsaysay").show();
    }


    var i = 1;
    var fd = new FormData();
    $scope.preview = function () {
        var r = new FileReader();
        var f = document.getElementById('uploadPic').files[0];
        fd.append("files", f);
        r.readAsDataURL(f);
        if (i < 5) {
            $(".a-upload").animate({left: (130 * (i ) + 30) + 'px'});
        } else if (i < 9) {
            $(".a-upload").animate({left: (130 * (i - 5) + 30) + 'px'}).animate({top: '450px'});
        } else if (i == 9) {
            $(".a-upload").hide();
        }
        r.onload = function () {
            document.getElementById("ava" + i).src = this.result;
            document.getElementById("ava" + (i + 1)).src = "../img/+.png";
            $("#preview" + (i + 1)).show();
            i++;
        }
    }

    $scope.publishsaysay = function () {

        // var files = document.querySelector('input[name="files"]').files;
        // for (var i = 0; i < files.length; i++) {
        //     fd.append("files", files[i]);
        //     $scope.img1 = files[i];
        // }
        fd.append("id", $scope.id);
        $http({
            method: 'POST',
            url: '../Publish/saysay ',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            alert("发布成功")
            location.reload();
        }, function errorCallback(response) {
            alert("发布失败")
        });
    }


    $http({
        method: 'GET',
        url: '../Twitter/searchTwitter'
    }).then(function successCallBack(response) {
        $rootScope.news = response.data
        $("#BriefDiv").show();
    },function errorCallBack() {
        alert("error")
    })


})


app.controller("selfpage",function ($scope,$rootScope,$http,$location) {

    $rootScope.showSelf=function (name,time,content,dimgs,avatar,articleUrl,urlDisplay) {
        $rootScope.visiable=true;


        $rootScope.DName = name;
        $rootScope.DTime = time;
        $rootScope.DContent = content;
        $rootScope.DImgs = dimgs;
        $rootScope.DAvatar = avatar;
        $rootScope.DAtricleUrl = articleUrl;
        $rootScope.UrlDispaly = urlDisplay;



        $("#publishsaysay").hide();
        $("#DetailDiv").show();



        $scope.changePic=function($event){
            var img=$event.srcElement || $event.target;
            angular.element("#bigimage")[0].src=img.src;
            angular.element("#js-imgview")[0].style.display="block";
            angular.element("#js-imgview-mask")[0].style.display="block";
        }
        //点击图片时放小显示图片
        $scope.closePic =function(){
            angular.element("#js-imgview")[0].style.display="none";
            angular.element("#js-imgview-mask")[0].style.display="none";

        }


    }
    $scope.jumpToUrl = function() {
        var path1 ="edit.html"
        window.open(path1)

    };

    $scope.changePage2 = function () {

        $("#SelfDiv").hide();
        $("#publishsaysay").show();
    }

    var i = 1;
    var fd = new FormData();
    $scope.preview = function () {
        var r = new FileReader();
        var f = document.getElementById('uploadPic').files[0];
        fd.append("files",f);
        r.readAsDataURL(f);
        if (i < 5) {
            $(".a-upload").animate({left: (130 * (i ) + 30) + 'px'});
        } else if (i < 9) {
            $(".a-upload").animate({left: (130 * (i - 5) + 30) + 'px'}).animate({top: '450px'});
        } else if (i == 9) {
            $(".a-upload").hide();
        }
        r.onload = function () {
            document.getElementById("ava" + i).src = this.result;
            document.getElementById("ava" + (i + 1)).src = "../img/+.png";
            $("#preview" + (i + 1)).show();
            i++;
        }
    }

    $scope.publishsaysay = function () {

        // var files = document.querySelector('input[name="files"]').files;
        // for (var i = 0; i < files.length; i++) {
        //     fd.append("files", files[i]);
        //     $scope.img1 = files[i];
        // }
        fd.append("id", $scope.id);
        $http({
            method: 'POST',
            url: '../Publish/saysay ',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            alert("发布成功")
            location.reload() ;
        }, function errorCallback(response) {
            alert("发布失败")
        });
    }


    $http({
        method:'GET',
        url:'../Twitter/searchSelf'
    }).then(function successCallBack(response) {
        $rootScope.self = response.data
        $rootScope.savatar = $rootScope.self[0].selfAvatar;
        $rootScope.sname = $rootScope.self[0].selfName;

        $("#Layer27").show();
        // for(var i = 0 ; i < $rootScope.self.length ; i++) {
        //     $scope.savatar = $rootScope.self[i].avatar;
        //     $scope.sname = $rootScope.self[i].name;
        // }
    }, function errorCallBack() {
        alert("error")
    })


})


app.filter('cut', function () {
    return function (value, wordwise, max, tail) {
        if (!value) return '';

        max = parseInt(max, 10);
        if (!max) return value;
        if (value.length <= max) return value;

        value = value.substr(0, max);
        if (wordwise) {
            var lastspace = value.lastIndexOf(' ');
            if (lastspace != -1) {
                value = value.substr(0, lastspace);
            }
        }

        return value + (tail || ' …');
    };
});

app.filter('trustHtml', function ($sce) {
    return function (input) {
        return $sce.trustAsHtml(input);
    }
});

// app.controller("detail",function ($scope,$rootScope) {
//     $scope.news1 = $rootScope.news;
// })


// app.factory('socket', function() {
//     var service = {};
//     service.ws = {};
//     var collection = [];
//
//
//     service.connect = function() {
//         this.ws = new WebSocket("ws://localhost:8080/zzlp/socketServer");
//         this.ws.onmessage = function(msg) {
//             alert(msg.data);
//             try {
//                 collection.push(msg.data);
//                // alert('roba: '+JSON.parse(msg.data).lat+' :: '+JSON.parse(msg.data).lng);
//             } catch(err) {
//                 console.log('err.message', err.message);
//                 alert(err.message);
//             }
//         };
//         this.ws.onerror = function(evt) {
//             alert('error: '+evt.data);
//         };
//     };
//     service.disconnect = function() {
//         if(this.ws != undefined && this.ws != null) {
//             this.ws.onclose();
//         }
//     };
//     return service;
// });


app.factory('MyData', function ($rootScope) {
    var dataStream = new WebSocket('ws://192.168.0.106:8080/zzlp/socketServer');
    var collection = [];

    dataStream.onmessage = function (msg) {

        var message = JSON.parse(msg.data);


        if ($("#targetId").html() == message.fromId) {
            if (message.type == "text") {
                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='chatTemplateExample2_files/cat.jpg'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + message.msg + " </div></span> </div> </div>");
                $(temp).html(message.msg);
            }
            else if (message.type == "img") {
                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='chatTemplateExample2_files/cat.jpg'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' src='https://gss1.bdstatic.com/-vo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=d1d11ecc3ea85edfee81f671283d6246/314e251f95cad1c8ca668bbb753e6709c83d5148.jpg'/></div></span> </div> </div>");
                $(temp).html("[图片]");
            } else if (message.type == "file") {
                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='chatTemplateExample2_files/cat.jpg'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='http://www.baidu.com'>下载</a><p>" + message.msg + "</p></div></span> </div> </div>");
                $(temp).html("[文件]");
            }
            localStorage.setItem($("#targetId").html(), $("#chatView").html());
            var div = document.getElementById("chatView");
            div.scrollTop = div.scrollHeight;
            var temp = "#" + message.fromId + "LastMessage";

        } else {
            if ((localStorage.getItem(message.fromId) == "") || (localStorage.getItem(message.fromId) == null)) {


                localStorage.setItem(message.fromId, "");
            }
            var temp = "#" + message.fromId + "LastMessage";
            $(temp).html(message.msg);
            $("#tempChatView").html(localStorage.getItem(message.fromId));
            $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
            $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img src='chatTemplateExample2_files/cat.jpg'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + message.msg + " </div></span> </div> </div>");
            localStorage.setItem(message.fromId, $("#tempChatView").html());
            $("#tempChatView").html("");
        }
        //alert(msg.data);

        collection.push(msg.data);
        $rootScope.$apply();
    }

    var methods = {
        collection: collection,
        get: function () {
            dataStream.send(JSON.stringify({action: 'get'}));
        }

    };
    return methods;
});
app.controller("zzty", function ($scope, $http, $interval) {


    $http({
        method: "GET",
        url: "../TeamExam/identity"
    }).then(function successCallback(response) {
        if (response.data == 1) {
            $("#student").show();
        } else if (response.data == 2) {
            $("#teacher").show();
        }
    }, function errorCallback(response) {

    });


    $scope.teamexam = function () {
        // cancel(promise);
        $http({
            method: 'GET',
            url: "../TeamExam/judgeStart"
        }).then(function successCallback(response) {
            if ("无法开始" == response) {
                $scope.teamquestions = response;
                // $scope.company = response.teamerId;
            } else {
                if (response.data.question != "请等待你的队友") {
                    $interval.cancel(teamtimerHandler)
                    teamcountDown(response.data.leftTime, response.data.leftTime);
                }
                $scope.teamquestions = response.data.question;
                $scope.company = response.data.teamerId;

            }
        }, function errorCallback(response) {
            $scope.teamquestions = "error";
        });
    };
    $scope.selfexam = function () {
        $http({
            method: 'GET',
            url: "../SelfExamTransation/judge"
        }).then(function successCallback(response) {
            if ("无法开始竞赛" == response) {
                $scope.selfquestions = response;
            } else {
                $interval.cancel(selftimerHandler);
                $scope.selfquestions = response.data.qstContent;
                selfcountDown(response.data.countdown, response.data.countdown);
            }
        }, function errorCallback(response) {
            $scope.selfquestions = "现在不能开始竞赛";
        });
    };

    var teamtimerHandler = null;
    var teamcountDown = function (second, time) {
        teamtimerHandler = $interval(function () {
            if (second > 0) {
                var h = Math.floor(second / 60 / 60 % 24);
                var m = Math.floor(second / 60 % 60);
                var s = Math.floor(second % 60);
                $scope.teamdescription = h + "时" + m + "分" + s + "秒";
                second--;
            } else {
                $interval.cancel(teamtimerHandler);
                $scope.teamdescription = "已结束";
                $scope.teamquestions = "现在不能开始竞赛";
            }
        }, 1000, time)
    }

    var selftimerHandler = null;
    var selfcountDown = function (second, time) {
        selftimerHandler = $interval(function () {
            if (second > 0) {
                var h = Math.floor(second / 60 / 60 % 24);
                var m = Math.floor(second / 60 % 60);
                var s = Math.floor(second % 60);
                $scope.selfdescription = h + "时" + m + "分" + s + "秒";
                second--;
            } else {
                $interval.cancel(selftimerHandler);
                $scope.selfdescription = "已结束";
                $scope.selfquestions = "现在不能开始竞赛";
            }
        }, 1000, time)
    }

    //文件上传
    $scope.teamsubmit = function () {
        var teamfd = new FormData();
        var teamfiles = document.querySelector('input[name="teamfiles"]').files;
        for (var i = 0; i < teamfiles.length; i++) {
            teamfd.append("files", teamfiles[i]);
        }
        $http({
            method: 'POST',
            url: '../TeamExam/uploadFile1',
            data: teamfd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            if ("success" == response.data.massage) {
                alert("文件提交成功")
                $("#selfexam").hide();
                $("#teamexam").hide();
            } else {
                alert("您已交过作业，请勿重复提交")
            }
        }, function errorCallback(response) {
            alert("无法提交")
        });
    };


    $scope.selfsubmit = function () {
        var selffd = new FormData();
        var selffiles = document.querySelector('input[name="selffiles"]').files;
        for (var i = 0; i < selffiles.length; i++) {
            selffd.append("files", selffiles[i]);
        }
        // fd.append("id", $scope.id);
        $http({
            method: 'POST',
            url: '../SelfExamTransation/submit1',
            data: selffd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            if ("success" == response.data.massage) {
                alert("文件提交成功")
                $("#selfexam").hide();
                $("#teamexam").hide();
            } else {
                alert("您已交过作业，请勿重复提交")
            }
        }, function errorCallback(response) {
            alert("无法提交")
        });
    }

});


app.controller("selfgrade", ["$scope", "$filter", "$http", function ($scope, $filter, $http) {

    $scope.selfsearch = function () {
        var fd = new FormData();
        $scope.dtt2 = $filter("date")($scope.selfdate, "yyyy-MM-dd");
        // alert($scope.dtt2)
        fd.append("date", $scope.dtt2)
        $http({
            method: 'POST',
            url: '../selfgread/Call',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            // alert(response.data);
            $scope.wpmagazine = response.data;
            // alert("success")
        }, function errorCallback(response) {
            alert("error")
        });
    }
}])

app.controller("teamgrade", ["$scope", "$filter", "$http", function ($scope, $filter, $http) {

    $scope.teamsearch = function () {
        var fd = new FormData();
        $scope.dt2 = $filter("date")($scope.teamdate, "yyyy-MM-dd");
        // alert($scope.dtt2)
        fd.append("date", $scope.dt2)
        $http({
            method: 'POST',
            url: '../teamgread/Call',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            // alert(response.data);
            $scope.wpmagazine = response.data;
            // alert("success")
        }, function errorCallback(response) {
            alert("error")
        });
    }
}])


app.controller('answers', ["$scope", "$http", function ($scope, $http) {

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); //匹配目标参数
        if (r != null)
            return unescape(r[2]);
        return null; //返回参数值
    }


    $scope.userid = getUrlParam('id');
    $scope.examdate = getUrlParam('date');
    $scope.operations = getUrlParam('operation');
    var json1 = new FormData();
    json1.append("userid", $scope.userid);
    json1.append("examdate", $scope.examdate);
    json1.append("operations", $scope.operations);
    $http({
        method: 'POST',
        url: '../answer/getmassage',
        data: json1,
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    }).then(function successCallback(response) {
        $scope.jsonObj = response.data;
        var branches;
        $.each($scope.jsonObj, function (key, value) {
            branches = "<li><span class='file'>" + key
                + "</span></li>";
            $("#browser").append(branches);
        })
    }, function errorCallback(response) {
        alert("error")
    });
    var json2 = new FormData();
    json2.append("userid", $scope.userid);
    $http({
        method: 'POST',
        url: '../answer/getname',
        data: json2,
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    }).then(function successCallback(response) {
        $scope.name = response.data;
    }, function errorCallback(response) {
        // alert("error")
    });

    $("#browser").on('click', '.file', function () {
        var tmp = $(this).text();
        $.each($scope.jsonObj, function (key, value) {
            if (tmp == key) {
                $("#div1").empty();
                $("#div1").append(value);
            }
        });

    });

    $scope.submit = function () {
        json1.append("comment", $scope.comment);
        json1.append("score", $('input:radio:checked').val());
        // alert($scope.comment);
        // alert($('input:radio:checked').val())
        $http({
            method: 'POST',
            url: '../answer/submit',
            data: json1,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            // $scope.name = response.data;
            // alert("success")
            window.close();//关闭当前窗窗口
        }, function errorCallback(response) {
            alert("error")
        });
    }
}]);
app.controller('Placement', ["$scope", "$http", function ($scope, $http) {

    $http({
        method: "GET",
        url: "../Placement/getall"
    }).then(function successCallback(response) {
        $scope.users = response.data;
    }, function errorCallback(response) {

    });

    $http({
        method: "GET",
        url: "../Placement/getclass"
    }).then(function successCallback(response) {
        $scope.clazzs = response.data;
    }, function errorCallback(response) {

    });

    $scope.Placement = function () {

        var fd = new FormData();

        fd.append("id", $scope.finallyuser);
        fd.append("clazz", $scope.finallyclazz)
        $http({
            method: 'POST',
            url: '../Placement/confirm',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            alert("success")
        }, function errorCallback(response) {
            alert("error")
        });

    }
}]);
app.controller('fenzu', ["$scope", "$http", function ($scope, $http) {


    $scope.fenzutijiao = function () {
        $("#table1 tr td:nth-child(3)").each(function () {
            // alert($(this).text().replace("|", "%7C"))
            var fd = new FormData();
            fd.append("group", $(this).text())
            //此处需转义
            // alert($(this).text())
            $http({
                method: 'POST',
                url: '../Cgroup/insert',
                data: fd,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            }).then(function successCallback(response) {
                // alert("success")

            }, function errorCallback(response) {
                // alert("error")
            });
        });
        location.reload();
    }
}])


app.controller('uploadCtrl', ["$scope", "$http", function ($scope, $http) {
    $scope.submit = function () {
        var fd = new FormData();
        var files = document.querySelector('input[name="files"]').files;
        for (var i = 0; i < files.length; i++) {
            fd.append("files", files[i]);
            $scope.img1 = files[i];
            // alert(files[i].data.path())
        }
        fd.append("id", $scope.id);
        $http({
            method: 'POST',
            url: '../TeamExam/uploadFile1',
            data: fd,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function successCallback(response) {
            alert("success")
        }, function errorCallback(response) {
            alert("error")
        });
    }
}]);

app.controller("logoutController", function ($scope,$http) {
    $scope.logout = function () {
        $http({
            url: '../login/logout',
        }).then(function successCallback(response) {
            window.location='login.html';
        }, function errorCallback(response) {

        });
    }
});
app.controller("mainAvaCtrl",function($scope,$http){
    $http({
        method:'GET',
        url:'../Twitter/mainHtmlAva'
    }).then(function successCallback(response) {
        $scope.ava = response.data
        $scope.mainAvatar = $scope.ava[0].mainAva;
    },function errorCallback(response) {
        alert("error")
    })
})